<template>
  <a-trigger :trigger="['click']" position="rt" v-model:popup-visible="visible">
    <div id="logo" @click="handleIconClick">
      <img alt="Logo" src="../assets/logo.png" width="36" height="36" />
    </div>
    <template #content>
      <div class="navigatorMenu">
        <a-doption>新建</a-doption>
        <a-doption @click="handleSaveClick">保存到电脑</a-doption>
        <a-doption @click="handleSaveRemoteClick">保存到远程</a-doption>
        <a-doption @click="handleOpenClick">打开本地文件</a-doption>
        <a-doption @click="loadRemove">打开远程文件</a-doption>
        <a-divider margin="1px" />
        <a-doption @click="handleSearchClick">查找</a-doption>
        <a-divider margin="1px" />
        <a-doption @click="handleOptionsClick">设置</a-doption>
        <!-- <a-doption @click="handleAboutClick">关于</a-doption> -->
      </div>
    </template>
  </a-trigger>
  <Settings ref="modal"></Settings>
  <a-modal v-model:visible="visible2" width="auto" @cancel="handleCancel" :on-before-ok="handleBeforeOk" unmountOnClose>
    <template #title> 保存到远程 </template>
    <div class="lis">

      <a-form :model="form" auto-label-width>




        <!-- <a-form-item field="name" label="Username">
          <a-input v-model="form.name" placeholder="please enter your username..." />
        </a-form-item> -->
        <a-row :gutter="24">

          <a-col :span="24">
            <a-form-item label="文件名：" :field="form.fileName">

              <a-input v-model="form.fileName" placeholder="要保存的文件名" allow-clear />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">

          <a-col :span="9">
            <a-form-item v-for="(post, index) of form.posts" :field="`posts[${index}].value`" :label="`${post.var}:`"
              :key="index">
              <a-input v-model="post.defaultValue" placeholder="变量的默认值" />
            </a-form-item>
          </a-col>
          <a-col :span="9">
            <a-form-item v-for="(post, index) of form.posts" :field="`posts[${index}].about`" :label="`变量说明:`"
              :key="index">

              <a-input v-model="post.about" />
              <!-- <a-checkbox  v-model="post.isExport">导出变量</a-checkbox> -->
            </a-form-item>
          </a-col>
          <a-col :span="3">
            <a-form-item v-for="(post, index) of form.posts" :field="`posts[${index}].isShow`" :label="`是否导出变量:`"
              :key="index">
              <a-checkbox v-model="post.isShow"></a-checkbox>
            </a-form-item>
          </a-col>
        </a-row>

      </a-form>
    </div>

  </a-modal>
</template>

<script setup>
import { Message } from '@arco-design/web-vue';
import Blockly from 'blockly';
import { v4 as uuidv4 } from 'uuid';
import { onMounted, ref, reactive, watch } from 'vue';
import { storeToRefs } from 'pinia'
// import parser from '@babel/parser';
// import { parser } from '@babel/parser';
// import traverse   from '@babel/traverse';

import axios from '../api/http';
import { useStore } from '../store/store';
import Settings from './Settings.vue';
import { extractVariablesAndComments } from '../util/utils';
const visible2 = ref(false);
const visible = ref();
const modal = ref();
const store = useStore();
const uuid = ref('');
const fileName = ref('');

// const { form } = storeToRefs(useStore());


const form = ref({
  fileName: '',
  posts: []
})


// watch(form, async (newQuestion, oldQuestion) => {

//   store.form = form;
// });

watch(form.value, async (newQuestion, oldQuestion) => {
  console.log('侦听器', newQuestion);
  store.form = [...newQuestion.posts];
})

function handleIconClick() {
  Blockly.hideChaff()
}


function handleSaveClick() {
  const json = Blockly.serialization.workspaces.save(store.workspaceSvg)
  const text = JSON.stringify(json)
  const blob = new Blob([text], { type: 'text/plain;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  console.log('程序数据', blob);
  const anchor = document.createElement('a');
  anchor.href = url;
  anchor.download = 'project.sb3';
  anchor.click();
  visible.value = false;
}
// 保存到远程
function handleSaveRemoteClick() {

  const json = Blockly.serialization.workspaces.save(store.workspaceSvg);
  console.log('变量:', json);

  const array = [];
  for (let i = 0; i < json?.variables?.length; i++) {
    const element = json.variables[i];
    if (form.value.posts.indexOf()) {

    }
    const index = form.value.posts.findIndex(obj => obj.var === element.name);

    if (index === -1) {
      array.push(
        {
          var: element.name,//变量名
          defaultValue: "0",//默认值
          about: '变量说明', //变量注释,
          isShow: true // 是否导出变量
        }
      );
    }
  }

  console.log('变量列表:', form.value.posts);
  form.value.posts.push(...array);
  const filteredArray = form.value.posts.filter(item => {
    return json?.variables?.some(obj => obj.name === item.var);
  });
  console.log('过滤列表', filteredArray);
  form.value.posts = [...filteredArray];
  visible2.value = true;
}

// 取消保存
const handleCancel = () => {
  visible2.value = false
}

// 保存按钮点击
const handleBeforeOk = async () => {
  const json = Blockly.serialization.workspaces.save(store.workspaceSvg);
  // console.log('代码:', json);
  // const array = [];
  // for (let i = 0; i < json?.variables?.length; i++) {
  //   const element = json.variables[i];

  //   array.push({
  //     defaultValue: 0,
  //     [element.name]: element.name
  //   });
  // }
  // console.log('变量列表:', form.value.posts);
  const result = extractVariablesAndComments(store.code);
 
  const text = JSON.stringify({
    file: json,
    code: store.code
  })
  const data = JSON.stringify({
    id: store.uuid,
    name: form.value.fileName,
    paramNames: JSON.stringify(form.value.posts.filter(item => item.isShow)),
    resultParamName: JSON.stringify(result),
    picPath: 'string',
    data: text
  })
  console.log('保存的程序:', data)

  const config = {
    // baseURL: '',
    method: 'post',
    url: '/scratch/save',
    data: data,
    headers: {
      'Content-Type': 'application/json'
    }
  }
  return await axios(config)
    .then((response) => {
      const res = response;
      console.log(res)
      if (res.success && res.code) {
        Message.success('保存成功')
        return true
      } else {
        Message.warning('保存失败:', res.msg)
        return false
      }
    })
    .catch((error) => {
      Message.error('保存错误:', res.msg)
      return false
    })

  // await new Promise(resolve => setTimeout(resolve, 3000));
  // return true;
  // prevent close
  // return false;
}

// 打开本地文件
function handleOpenClick() {
  const input = document.createElement('input')
  input.setAttribute('type', 'file')
  input.setAttribute('name', 'file')
  input.setAttribute('visibility', 'hidden')
  input.setAttribute('accept', '.sb3')
  input.addEventListener('change', function () {
    const file = this.files[0]
    const reader = new FileReader()
    reader.addEventListener('load', function () {
      const json = JSON.parse(this.result)
      Blockly.serialization.workspaces.load(json, store.workspaceSvg)
    })
    reader.readAsText(file)
  })
  input.click()
  visible.value = false
}


function loadRemove(id) {
  const config = {
    // baseURL: '',
    method: 'get',
    url: `/scratch/detail?id=${id}`,
    headers: {
      'Content-Type': 'application/json'
    }
  }
  axios(config)
    .then((response) => {
      const json = response;
      console.log(json);
      if (json.success && json.data.data !== null) {
        form.value.fileName = json.data.name;
        form.value.posts = [...JSON.parse(json.data.paramNames)];
        store.uuid = json.data.id;
        Blockly.serialization.workspaces.load(JSON.parse(json.data.data).file, store.workspaceSvg)
        Message.success('打开成功')
      } else {
        Message.warning('打开失败')
      }
    })
    .catch(function (error) {
      Message.warning('打开失败')
      console.log(error)
    })
}

onMounted(() => {
  if (store.uuid) {
    loadRemove(store.uuid)
  } else {
    store.uuid = uuidv4();
  }

  // 监听变量创建事件
  store.workspaceSvg.addChangeListener((event) => {
    if (event instanceof Blockly.Events.VarCreate) {
      console.log('变量添加:', event.varId);
    }
  });

  // 监听变量删除事件
  store.workspaceSvg.addChangeListener((event) => {
    if (event instanceof Blockly.Events.VarDelete) {
      console.log('变量删除:', event.varId);
    }
  });
  // console.log('token:', store.token, store.uuid);
})
function handleSearchClick() {
  store.searchVisible = true
  visible.value = false
}

function handleOptionsClick() {
  modal.value.handleClick()
  visible.value = false
}

function handleAboutClick() {
  visible.value = false
}





</script>

<style>
#logo {
  position: absolute;
  z-index: 4;
  top: 0;
  left: 0;

  width: 36px;
  height: 36px;
  padding: 12px;

  background-color: var(--color-bg-2);
}

.lis {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  /* gap: 20px; */
}

.navigatorMenu {
  overflow: hidden;

  box-sizing: border-box;
  padding: 12px 16px;

  font-size: 14px;
  line-height: 1.5715;
  color: var(--color-text-2);

  background-color: var(--color-bg-popup);
  border: 1px solid var(--color-neutral-3);
  border-radius: var(--border-radius-medium);
  box-shadow: 0 -2px 5px rgb(0 0 0 / 10%);

  animation: show-dropdown cubic-bezier(0.3, 1.3, 0.3, 1) 400ms forwards !important;

  /* >li {
    -webkit-tap-highlight-color: transparent;
  } */
}

@keyframes show-dropdown {
  0% {
    width: 0;
    height: 0;
  }

  100% {
    width: 150px;
    height: 288px;
  }
}
</style>
